<!--
  * 角色表
  *
  * @Author:    zhoujk
  * @Date:      2025-01-23 04:08:27

-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item label="输入查询" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="queryForm.nameLeftLike" placeholder="角色名称" />
      </a-form-item>
      <a-form-item label="角色状态" class="smart-query-form-item">
        <SmartEnumSelect width="200px" v-model:value="queryForm.status" enumName="ZZB_ENABLE_STATUS_ENUM" placeholder="状态" />
      </a-form-item>
      <a-form-item class="smart-query-form-item">
        <a-button type="primary" @click="onSearch">
          <template #icon>
            <SearchOutlined />
          </template>
          查询
        </a-button>
        <a-button @click="resetQuery" class="smart-margin-left10">
          <template #icon>
            <ReloadOutlined />
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="showForm" type="primary" size="small">
          <template #icon>
            <PlusOutlined />
          </template>
          新建
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <!-- <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.SYSTEM.ROLE" :refresh="queryData" /> -->
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->

    <!---------- 表格 begin ----------->
    <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :loading="tableLoading" :pagination="false">
      <template #bodyCell="{ text, record, column }">
        <template v-if="column.dataIndex === 'status'">
          <div v-if="record.id === '0000000000000' || record.id === '0000000000001'">-</div>
          <a-switch
            :checked="text === ZZB_ENABLE_STATUS_ENUM.ENABLE_STATUS.value"
            @change="(checked) => handleStatusChangeConfirm(checked, record)"
            :loading="record.statusLoading"
            v-if="record.id !== '0000000000000' && record.id !== '0000000000001'"
          />
        </template>
        <template v-if="column.dataIndex === 'action'">
          <div class="smart-table-operate">
            <a-button @click="insertUserRole(record)" type="link" v-privilege="'user:role:batch_insert'"> 添加人员 </a-button>
            <a-button @click="deleteUserRole(record)" type="link" v-privilege="'user:role:delete'"> 移除人员 </a-button>
            <a-button @click="showRoleForm(record)" type="link" v-if="record.id !== '0000000000000' && record.id !== '0000000000001'"
              >设置权限</a-button
            >
            <a-button @click="showForm(record)" type="link" v-if="record.id !== '0000000000000' && record.id !== '0000000000001'">编辑</a-button>
          </div>
        </template>
      </template>
    </a-table>
    <!---------- 表格 end ----------->

    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize"
        v-model:current="queryForm.pageNo"
        v-model:pageSize="queryForm.pageSize"
        :total="total"
        @change="queryData"
        @showSizeChange="queryData"
        :show-total="(total) => `共${total}条`"
      />
    </div>

    <RoleForm ref="formRef" @reloadList="queryData" />
    <UserTableSelectModal ref="selectUserModal" @selectData="selectData" />
    <UserTableDeleteModal ref="deleteUserModal" />
    <RoleSetting ref="roleSettingModal" />
  </a-card>
</template>
<script setup>
  import { reactive, ref, onMounted, createVNode } from 'vue'
  import { message, Modal } from 'ant-design-vue'
  import _ from 'lodash'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import { roleApi } from '/@/api/system/b-agent/role-api'
  import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const'
  import { smartSentry } from '/@/lib/smart-sentry'
  import TableOperator from '/@/components/support/table-operator/index.vue'
  import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue'
  import RoleForm from './role-form.vue'
  import { ZZB_ENABLE_STATUS_ENUM } from '/@/constants/system/system-const.js'
  import UserTableSelectModal from '/@/components/system/b-agent/user-table-select-modal/index.vue'
  import UserTableDeleteModal from './components/role-user-list/index.vue'
  import RoleSetting from './components/role-setting/index.vue'
  import dayjs from 'dayjs'
  import { userApi } from '/@/api/system/b-agent/user-api.js'
  import { TABLE_ID_CONST } from '/@/constants/support/table-id-const.js'
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
  //import FilePreview from '/@/components/support/file-preview/index.vue'; // 图片预览组件

  // ---------------------------- 表格列 ----------------------------

  const columns = ref([
    {
      title: '角色名称',
      dataIndex: 'name',
      ellipsis: true,
    },
    {
      title: '角色人员',
      dataIndex: 'memberNum',
      ellipsis: true,
    },
    {
      title: '角色描述',
      dataIndex: 'desc',
      ellipsis: true,
    },
    {
      title: '更新时间',
      dataIndex: 'uTime',
      customRender: (column) => dayjs(column.text).format('YYYY-MM-DD HH:mm'),
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 300,
    },
  ])

  // ---------------------------- 查询数据表单和方法 ----------------------------

  const queryFormState = {
    nameLeftLike: undefined, //角色名称
    status: undefined, //状态
    pageNo: 1,
    pageSize: 10,
  }
  // 查询表单form
  const queryForm = reactive({ ...queryFormState })
  // 表格加载loading
  const tableLoading = ref(false)
  // 表格数据
  const tableData = ref([])
  // 总数
  const total = ref(0)

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.pageSize
    Object.assign(queryForm, queryFormState)
    queryForm.pageSize = pageSize
    queryData()
  }

  // 搜索
  function onSearch() {
    queryForm.pageNo = 1
    queryData()
  }

  // 查询数据
  async function queryData() {
    tableLoading.value = true
    try {
      let queryResult = await roleApi.page(queryForm)
      tableData.value = queryResult.data

      total.value = queryResult.total
    } catch (e) {
      smartSentry.captureError(e)
    } finally {
      tableLoading.value = false
    }
  }

  // ---------------------------- 添加/修改 ----------------------------
  const formRef = ref()

  function showForm(data) {
    formRef.value.show(data)
  }

  // ----------------------- 添加成员 ---------------------------------
  let selectRoleId = ref('')
  const selectUserModal = ref()

  async function insertUserRole(record) {
    selectRoleId.value = record.id
    let res = await userApi.list({ roleId: selectRoleId.value, showRoleFlag: false })
    let selectedIdList = res.data.map((e) => e.id) || []
    selectUserModal.value.showModal(selectedIdList)
  }

  async function selectData(list) {
    if (_.isEmpty(list)) {
      message.warning('请选择角色人员')
      return
    }
    SmartLoading.show()
    try {
      let params = {
        userIds: list,
        roleId: selectRoleId.value,
      }
      await userApi.batchInsertRoleUser(params)
      message.success('添加成功')
      await queryData()
    } catch (e) {
      smartSentry.captureError(e)
    } finally {
      SmartLoading.hide()
    }
  }

  // ----------------------- 移除成员 ---------------------------------
  const deleteUserModal = ref()

  async function deleteUserRole(record) {
    deleteUserModal.value.showModal(record.id)
  }

  // ----------------------- 角色权限设置 ---------------------------------
  const roleSettingModal = ref()

  async function showRoleForm(record) {
    roleSettingModal.value.showModal(record.id)
  }

  // ---------------------------- 更新状态 ----------------------------
  const handleStatusChangeConfirm = async (checked, record) => {
    Modal.confirm({
      title: '状态变更',
      icon: createVNode(ExclamationCircleOutlined),
      content: `确认修改"${record.name}"状态为${checked ? '启用' : '禁用'}`,
      okText: '确认',
      cancelText: '取消',
      onOk() {
        handleStatusChange(checked, record)
      },
    })
  }

  async function handleStatusChange(checked, record) {
    // 保存原始值用于错误回滚
    const originalStatus = record.status
    // 将布尔值转换为 0/1
    const targetStatus = checked ? ZZB_ENABLE_STATUS_ENUM.ENABLE_STATUS.value : ZZB_ENABLE_STATUS_ENUM.DISABLE_STATUS.value
    try {
      record.statusLoading = true

      const response = await roleApi.updateStatus({ id: record.id, status: targetStatus })
      if (response && response.code === 200) {
        // 更新本地状态
        record.status = targetStatus
        message.success('状态更新成功')
      } else {
        message.error('状态更新失败')
        // 如果更新失败，恢复原状态
        record.status = originalStatus
      }
    } catch (e) {
      smartSentry.captureError(e)
      record.status = originalStatus
    } finally {
      record.statusLoading = false
    }
  }

  onMounted(queryData)
</script>
